package pl.polidea.imf.common.java.impl.http;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.io.HttpConnection;

public class ConnectionTimeOutWatchDog extends TimerTask {
	private HttpConnection watchedConnection;
	boolean isCanceled = false;
	private Timer timer = null;

	public ConnectionTimeOutWatchDog(HttpConnection connectionToWatch) {
		watchedConnection = connectionToWatch;
	}

	public synchronized void watch() {
		if (timer == null) {
			timer = new Timer();
			timer.schedule(this, GenericHttpConnectionImpl.HTTP_CONNECTION_TIMEOUT);
		}
	}

	public synchronized void run() {
		if (watchedConnection != null && !isCanceled) {
			try {
				watchedConnection.close();
			} catch (IOException e) {
				
			}
		}
	}

	public synchronized boolean cancel() {
		isCanceled = true;
		return super.cancel();
	}
}